<template>
  <div class="login-container">
    <div class="content">
      <div class="logo">
        <img src="/favicon.ico" alt="logo" />
      </div>
      <div class="title">
        {{ $t("login.welcome") }}
        <!-- 欢迎登录 -->
      </div>
      <!-- <div class="btns">
				<button @click="loginTyle = 1" :class="loginTyle == 1 ? 'active' : ''">手机号登录</button>
				<button @click="loginTyle = 2" :class="loginTyle == 2 ? 'active' : ''">邮箱登录</button>
			</div> -->

      <!-- 输入框from区域 -->
      <loginContent ref="loginContentRef" :loginTyle="loginTyle" />

      <!-- 新增功能区域 -->
      <div class="agreement-forgot">
        <div class="agreement">
          <el-checkbox v-model="agreementChecked" id="agreement">
            {{ $t("login.agreementPrefix") }}
            <span
              class="agreement-link"
              @click.stop="goAgreement('privacyPolicy')"
            >
              《{{ $t("companyIntroduction.privacyPolicy") }}》
            </span>
            {{ $t("login.agreementAnd") }}
            <span
              class="agreement-link"
              @click.stop="goAgreement('userAgreement')"
            >
              《{{ $t("companyIntroduction.userAgreement") }}》
            </span>
          </el-checkbox>
        </div>
        <span class="forgot" @click="goForgot">
          {{ $t("login.forgot") }}
          <!-- 忘记密码？ -->
        </span>
      </div>
      <button
        class="login-btn"
        @click="handleSubmit"
        :class="{ 'login-btn-active': isDisbled }"
        v-loading="btnLoading"
        :disabled="btnLoading"
      >
        {{ $t("login.loginBtn") }}
        <!-- 登录 -->
      </button>
      <div class="register" @click="goEnroll">
        {{ $t("login.register") }}
        <!-- 没有账号？现在注册 -->
      </div>
      <div class="back-home">
        <svg-icon name="back" class="back-home-icon" @click="goHome"></svg-icon>
        <span @click="goHome"
          >{{ $t("login.backHome") }}
          <!-- 返回首页 --></span
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import loginContent from "./components/loginContent.vue";
import { validateEmail } from "~/utils/utils";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { $navigate } = useNuxtApp();
import { userLogin, getUserInfoPermission } from "~/apis/web.js";
const userStore = useStore.userStore();
const routeStore = useStore.routerStore();
const { t } = useI18n();
// 检查token，如果有token就跳转到首页
onMounted(() => {
  const token = useCookie("token").value || userStore.token;
  if (token) {
    $navigate(routeStore.indexRoute);
  }
});

definePageMeta({
  layout: false,
  ssr: true, // 必须为 true
});
const btnLoading = ref(false);
const loginContentRef = ref(null);
const loginTyle = ref(2); // 1: 手机号登录, 2: 邮箱登录
const userInfo = ref(null);
// 隐私协议单选框
const agreementChecked = ref(false);

// 点击登录按钮
const handleSubmit = () => {
  btnLoading.value = true;
  if (!loginContentRef.value || !loginContentRef.value.loginForm) {
    btnLoading.value = false;
    return false;
  }
  const { loginForm } = loginContentRef.value;
  console.log("loginForm", loginForm);
  if (loginTyle.value == 2) {
    if (!validateEmail(loginForm.email)) {
      ElMessage.error(t("login.emailInvalid"));
      btnLoading.value = false;
    } else {
      // 获取租户ID
      userLogin({
        username: loginForm.email,
        password: loginForm.password,
      })
        .then((res) => {
          if (res.code == 0) {
            userInfo.value = Object.assign(res.data);
            fetchUserPermissions(userInfo.value);
          }
        })
        .catch((error) => {
          console.log("error", error);
          btnLoading.value = false;
        });
    }
  }
};
// 登录用户的权限信息
const fetchUserPermissions = async (params) => {
  // 设置token
  await userStore.setToken(params.accessToken);
  getUserInfoPermission()
    .then((res) => {
      if (res.code == 0) {
        userInfo.value = Object.assign(userInfo.value, res.data.user);
        console.log("userInfo.value", userInfo.value);
        userStore.setUser(userInfo.value);
        btnLoading.value = false;
        // 登录到admin

        const route = useRoute();
        const { $navigate } = useNuxtApp();
        // 登录成功后：
        // 获取编码后的redirect参数，并解码
        const encodedRedirect = route.query.redirect;
        const redirect = encodedRedirect
          ? decodeURIComponent(encodedRedirect)
          : routeStore.indexRoute;
        $navigate(redirect, true);
      }
    })
    .catch((error) => {
      console.log("error", error);
      btnLoading.value = false;
    });
};

const isDisbled = computed(() => {
  if (!loginContentRef.value || !loginContentRef.value.loginForm) {
    return false;
  }
  const { loginForm } = loginContentRef.value;
  if (loginTyle.value == 1) {
    // 手机号登录，判断手机号、密码和协议
    return !!(loginForm.phone && loginForm.password && agreementChecked.value);
  } else {
    // 邮箱登录，假设需要邮箱、密码和协议
    return !!(loginForm.email && loginForm.password && agreementChecked.value);
  }
});

// 返回首页
const goHome = () => {
  $navigate("/web");
};
// 注册

const goEnroll = () => {
  $navigate("/login/enroll");
};

const goForgot = () => {
  $navigate("/login/forgetPassword");
};

const goAgreement = (params) => {
  // 跳转到协议页面
  $navigate(`/web/companyIntroduction/${params}`);
};
</script>

<style lang="less" scoped>
.login-container {
  width: 100%;
  height: 100%;
  background-color: #000;
  display: flex;
  justify-content: center;
  align-items: center;

  .content {
    width: 574px;
    padding: 20px 70px;
    box-sizing: border-box;
    background-color: #ffffff;

    .logo {
      height: 66px;
      margin: 0 auto;
      text-align: center;
      img {
        height: 100%;
      }
    }

    .title {
      font-family: Poppins, Poppins;
      font-weight: 500;
      font-size: 26px;
      color: #111111;
      text-align: center;
      margin: 20px auto 43px;
    }

    .btns {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;

      button {
        border: none;
        width: 50%;
        background: #c3c3c3;
        padding: 16px 0;
        box-sizing: border-box;
        font-family: Avenir, Avenir;
        font-weight: normal;
        font-size: 16px;
        color: #ffffff;
        cursor: pointer;
      }

      .active {
        background: #1e2021;
      }
    }

    .agreement-forgot {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-top: 24px;

      .agreement {
        display: flex;
        align-items: center;
        width: 300px;
        flex-wrap: wrap;
        // 未选中时文字样式
        :deep(.el-checkbox__label) {
          font-family: Poppins, Poppins;
          font-weight: 300;
          font-size: 12px;
          color: #656c7e;
          display: flex;
          flex-wrap: wrap;
          line-height: 20px;
        }
      }
      .forgot {
        flex: 1;
        font-family: Poppins, Poppins;
        font-weight: 300;
        font-size: 14px;
        color: #1e2021;
        cursor: pointer;
        text-align: right;
      }
    }

    .login-btn {
      width: 100%;
      background: #d3d3d3;
      border-radius: 0px 0px 0px 0px;
      padding: 13px 0;
      box-sizing: border-box;
      border: none;
      font-family: Poppins, Poppins;
      font-weight: 400;
      font-size: 16px;
      color: #ffffff;
      margin-top: 40px;
      cursor: no-drop;
    }

    .login-btn-active {
      cursor: pointer;
      background: var(--theme-gradient-bg);
    }

    .register {
      font-family: Poppins, Poppins;
      font-weight: 400;
      font-size: 16px;
      color: var(--el-color-primary);
      text-align: center;
      margin-top: 16px;
      cursor: pointer;
    }

    .back-home {
      text-align: center;
      margin-top: 45px;

      .back-home-icon {
        font-size: 19px;
        margin-right: 20px;
        cursor: pointer;
      }

      span {
        font-family: Poppins, Poppins;
        font-weight: 400;
        font-size: 16px;
        color: #1e2021;
        cursor: pointer;
      }
    }
  }
}
</style>
